﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chbl.Models;

namespace Chbl.ViewModels
{
    public class Standings
    {
        private Dictionary<int, TeamStanding> StandingsDict { get; set; }

        public Standings(SeasonDivision seasonDivision)
        {
            SeasonDivision = seasonDivision;
            StandingsDict = new Dictionary<int, TeamStanding>();
            foreach (var team in seasonDivision.Teams)
            {
                StandingsDict.Add(team.Id, new TeamStanding {Team = team, LostGames = 0, PointsScore = 0, PointsSkip = 0, WonGames = 0});
            }
        }
        public SeasonDivision SeasonDivision { get; private set; }
        
        public void ProcessGame(Game game)
        {
            if (!(game.HomeScore.HasValue && game.RoadScore.HasValue))
                return;

            var homeTeamStanding = StandingsDict[game.HomeTeamId];
            homeTeamStanding.PointsScore += game.HomeScore.Value;
            homeTeamStanding.PointsSkip += game.RoadScore.Value;

            var roadTeamStanding = StandingsDict[game.RoadTeamId];
            roadTeamStanding.PointsScore += homeTeamStanding.PointsSkip;
            roadTeamStanding.PointsSkip += homeTeamStanding.PointsScore;
            if (game.HomeScore.Value > game.RoadScore.Value )
            {                
                homeTeamStanding.WonGames++;
                roadTeamStanding.LostGames++;
            }
            else
            {
                homeTeamStanding.LostGames++;
                roadTeamStanding.WonGames++;
            }
        }

        public ICollection<TeamStanding> GetStandings()
        {
            var standingList = StandingsDict.Values.ToList();
            standingList.Sort(CompareTeamStanding);
            return standingList;
        }

        private static int CompareTeamStanding(TeamStanding left, TeamStanding right)
        {
            var leftWinPercentage = (float)left.WonGames/(left.WonGames + left.LostGames);
            var rightWinPercentage = (float) right.WonGames/(right.WonGames + right.LostGames);
            if (leftWinPercentage > rightWinPercentage)
                return -1;
            if (leftWinPercentage < rightWinPercentage)
                return 1;
            
            if (left.PointsDifference > right.PointsDifference)
                return -1;
            if (left.PointsDifference < right.PointsDifference)
                return 1;
            return 0;
        }

    }
}